<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label>
            <ARangePicker
              v-model="searchFrom.createdDt"
              :placeholder="['创建日期', '创建日期']"
              value-format="YYYY-MM-DD"
            />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.feeCategory" placeholder="费用分类" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.feeUsage" placeholder="费用用途" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.usedObj" placeholder="作用对象" allow-clear />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 3])" type="outline" @click="openEdit('新增')">新增</AButton>
          <!-- <tableImp
            imp-url="/produce/erpCustomerImport"
            :file-temp="() => onExport('template')"
          ></tableImp> -->
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable :pagination="false" :data="tableData" :bordered="{ cell: true }" column-resizable>
        <template #columns>
          <ATableColumn title="交易时间" data-index="tradeDt" :width="170">
            <template #cell="{ record }">
              {{ dayjs(record.tradeDt).format('YYYY-MM-DD') }}
            </template>
          </ATableColumn>
          <ATableColumn title="帐户名称" data-index="accountName" :width="255"></ATableColumn>
          <ATableColumn title="帐户号" data-index="bankAccount" :width="255"></ATableColumn>
          <ATableColumn title="费用分类" data-index="feeCategory" :width="255"></ATableColumn>
          <ATableColumn title="费用用途" data-index="feeUsage" :width="180"></ATableColumn>
          <ATableColumn title="收入" data-index="incomeAmt" :width="130"></ATableColumn>
          <ATableColumn title="支出" data-index="expendAmt" :width="100" align="center">
          </ATableColumn>
          <ATableColumn title="账户余额" data-index="accountBalance" :width="100" align="right">
            <template #cell="{ record }">
              {{ `${formatPrice(record.accountBalance)}` }}
            </template>
          </ATableColumn>
          <ATableColumn title="作用对象" data-index="usedObj" :width="120"></ATableColumn>
          <ATableColumn title="附件" data-index="fileList" :width="130" align="center">
            <template #cell="{ record }">
              <ADropdown
                v-if="!isEmpty(record.fileList)"
                @select="(fileUrl: any) => openFlie(record, fileUrl)"
              >
                <ALink>{{ record.fileList.length }}</ALink>
                <template #content>
                  <ADoption
                    v-for="(item, index) in record.fileList"
                    :key="index"
                    :value="item.fileUrl"
                  >
                    {{ item.fileName }}
                  </ADoption>
                </template>
              </ADropdown>
            </template>
          </ATableColumn>
          <ATableColumn title="备注" data-index="remark" :width="200"></ATableColumn>
          <ATableColumn
            v-if="isAuth([1, 3])"
            title="操作"
            :width="145"
            align="center"
            fixed="right"
          >
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="getTableData"
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import dayjs from 'dayjs'
import { isEmpty } from 'lodash-es'
// import tableImp from '@renderer/components/table/import.vue'
import { Message, Modal } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  delAccount,
  getAccountAllList,
  getAccountPageList,
  AccountListSearch,
  AccountResItem
} from '@renderer/api/accountFlowDetails'
import { downloadByteFile, formatPrice } from '@renderer/utils/mixins'

const searchFrom = ref<AccountListSearch>({
  tradeType: 0,
  createdDt: []
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<AccountResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})

onMounted(() => {
  getTableData()
})

async function getTableData() {
  const [createdStartDate, createdEndDate] = searchFrom.value.createdDt! || []
  searchFrom.value.createdStartDate = createdStartDate
    ? dayjs(createdStartDate).format('YYYY-MM-DD')
    : ''
  searchFrom.value.createdEndDate = createdEndDate ? dayjs(createdEndDate).format('YYYY-MM-DD') : ''
  const res = await getAccountPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

function onSearch() {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {
    tradeType: 0,
    createdDt: []
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {
    accountTradeDetailId: '',
    bankAccount: '',
    feeCategory: '',
    feeUsage: '',
    incomeAmt: 0,
    expendAmt: 0,
    accountBalance: 0,
    usedObj: '',
    tradeType: 0,
    remark: '',
    tenantId: 0,
    accountName: ''
  }
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref<AccountResItem>()

function rowEvent(row: AccountResItem, type: string) {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delAccount({ accountTradeDetailId: row.accountTradeDetailId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    default:
      break
  }
}

function openFlie(record: AccountResItem, flieUrl: any) {
  const temp = record.fileList?.find((item) => item.fileUrl === flieUrl)
  if (temp) {
    downloadByteFile(temp)
  }
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '创建日期', value: 'createdDt', width: 180 },
    { title: '费用分类', value: 'customerName', width: 180 },
    { title: '费用用途', value: 'customerAddress', width: 180 },
    { title: '收入', value: 'incomeAmt' },
    { title: '支出', value: 'expendAmt' },
    { title: '账户余额', value: 'payeeAcctBank' },
    { title: '作用对象', value: 'contactName' },
    { title: '备注', value: 'contactPhone', width: 180 }
  ]
  let excelData: AccountResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '公帐数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        if (searchFrom.value.createdDt) {
          ;[searchFrom.value.createdStartDate, searchFrom.value.createdEndDate] =
            searchFrom.value.createdDt!
          searchFrom.value.createdStartDate = dayjs(searchFrom.value.createdStartDate).format(
            'YYYY-MM-DD'
          )
          searchFrom.value.createdEndDate = dayjs(searchFrom.value.createdEndDate).format(
            'YYYY-MM-DD'
          )
        }
        const res = await getAccountAllList(searchFrom.value)
        excelData = res.data.list.map((item, index) => {
          item.index = index + 1
          return item
        })
      }
      break
    case 'template':
      fileTitle = '公帐导入模板'
      excelData = [
        {
          bankAccount: '365966588745',
          feeCategory: '货款',
          feeUsage: '销售订单货款',
          incomeAmt: 0,
          expendAmt: 0,
          accountBalance: 0,
          usedObj: 'XXX公司',
          tradeType: 0,
          remark: '',
          tenantId: 0,
          accountName: ''
        }
      ]
      break

    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
    exportLoad.value = false
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
